<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\web\controller;

use app\common\builder\ZBuilder;

use think\Db;
use app\common\model\Package as Package_Model;
use app\common\model\PackageItem as Item_Model;
use app\common\model\Goods as Goods_Model;
use app\common\model\Project as Project_Model;

class Package extends Auth
{

    /**
     * 套餐列表
     * @return mixed
     * @throws \think\Exception
     */
    public function index(){
        if ($this->request->isPost()) {
            // 表单数据
            $getData = $this->request->post();
            $limit = $this->request->post('limit');
            $data_list = Package_Model::order('id desc')->paginate($limit)->each(function ($item){
                $goods = Db::name('qt_data_package_item')->where('package_id',$item['id'])->column('name');
                $item['project_name'] = implode(',',$goods);
                unset($item['string']);
            });

            $this->result('请求成功',$data_list,200);
        }
        $this->result('请求错误','',204);
    }

    /**
     * 添加套餐
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $getData = $this->request->post();

            $validate = new \app\web\validate\Package();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $info = Package_Model::get(['name'=>$getData['name']]);
            if ($info)$this->result('套餐名称已存在', '', 200);
            $projectRes = json_decode($getData['project_name'],true);
            $i = 0;
            $j = 0;
            $goods = [];
            $project = [];
            foreach ($projectRes as $key=>$value){
                $productIDs = explode(',',$value['id']);
                foreach ($productIDs as $k=>$v){
                    $product = explode('-',$v);
                    if($product[0] = 'project'){
                        $project[$i]['id'] = $product[1];
                        $project[$i]['type'] = 'project';
                        $project[$i]['number'] = $value['number'];
                        $i++;
                    }elseif($product[0] = 'goods'){
                        $goods = Db::name('qt_goods')->field('name,status')->where(['id'=>$product[1]])->find();
                        if($goods['status'] == '0'){
                            $this->result('【'.$goods['name'].'】不可售，无法添加套餐', '', 204);
                        }
                        $goods[$j]['id'] = $product[1];
                        $goods[$j]['type'] = 'goods';
                        $goods[$j]['number'] = $value['number'];
                        $j++;
                    }
                }
                $key = array_column($project,'id');
                array_multisort($key,SORT_ASC,$project);
                $projectPackData = [];
                foreach ($project as $k=>$v){
                    $projectPackData[$k]= $v['id'].'-project-'.$v['number'];
                }
                $key = array_column($goods,'id');
                array_multisort($key,SORT_ASC,$goods);
                $goodsStringData = [];
                foreach ($goods as $k=>$v){
                    $goodsStringData[$k]= $v['id'].'-goods-'.$v['number'];
                }
                $stringData = array_merge($projectPackData,$goodsStringData);
                $string = implode(',',$stringData);

            }
            $getData['string'] = $string;
            $getData['store_id'] = $this->userInfo['store_id'];
            try{
                $packageID = Db::name('qt_data_package')->insertGetId($getData);
                $goods = [];
                $i = 0;
                foreach ($projectRes as $key=>$value){
                    $productIDs = explode(',',$value['id']);
                    foreach ($productIDs as $k=>$v){
                        $product = explode('-',$v);
                        $name = explode(',',$value['name']);
                        $goods[$i]['package_id'] = $packageID;
                        $goods[$i]['store_id'] = $this->userInfo['store_id'];
                        $goods[$i]['item_id'] = $product[1];
                        $goods[$i]['item_type'] = $product[0];
                        $goods[$i]['name'] = $name[$k];
                        $goods[$i]['number'] = $value['number'];
                        $goods[$i]['price'] = $value['price'];
                        $goods[$i]['creat_time'] = time();
                        $i ++;
                    }
                }
                Db::name('qt_data_package_item')->insertAll($goods);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                $this->result('新增失败','',204);
            }
            $this->result('新增成功','',200);

        }
        $this->result('无效的请求','',204);
    }


    /**
     * 编辑套餐
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数','',204);
            }
            $data = Package_Model::get($getData['id']);
            $project = Db::name('qt_data_package_item')
                ->field('id as package_item_id,package_id,item_id,item_type,name,price,number')
                ->where('package_id',$data['id'])
                ->group('package_id')
                ->select();
            if(!empty($project)){
                foreach ($project as $key=>$value){
                    $res = Db::name('qt_data_package_item')->where('package_id',$data['id'])->select();
                    $name = [];
                    $id = [];
                    foreach ($res as $k=>$v){
                        $name[$k] = $v['name'];
                        $id[$k] = $v['item_type'].'-'.$v['item_id'];
                    }
                    $project[$key]['name'] = implode(',',$name);
                    $project[$key]['id'] = implode(',',$id);
                }
                $data['project_name'] = $project;
            }
            $this->result('查询成功',$data,200);
        }
    }


    /**
     * 修改套餐
     * @return mixed
     * @throws \think\Exception
     */
    public function save()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $getData = $this->request->post();

            $validate = new \app\web\validate\Package();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $projectRes = json_decode($getData['project_name'],true);
            $i = 0;
            $j = 0;
            foreach ($projectRes as $key=>$value){
                $productIDs = explode(',',$value['id']);
                $project = [];
                $goods = [];
                foreach ($productIDs as $k=>$v){
                    $product = explode('-',$v);
                    if($product[0] == 'project'){
                        $project[$i]['id'] = $product[1];
                        $project[$i]['type'] = 'project';
                        $project[$i]['number'] = $value['number'];
                        $i++;
                    }
                    if($product[0] == 'goods'){
                        $goods[$j]['id'] = $product[1];
                        $goods[$j]['type'] = 'goods';
                        $goods[$j]['number'] = $value['number'];
                        $j++;
                    }
                }
                $key = array_column($project,'id');
                array_multisort($key,SORT_ASC,$project);
                $projectPackData = [];
                foreach ($project as $k=>$v){
                    $projectPackData[$k]= $v['id'].'-project-'.$v['number'];
                }
                $key = array_column($goods,'id');
                array_multisort($key,SORT_ASC,$goods);
                $goodsStringData = [];
                foreach ($goods as $k=>$v){
                    $goodsStringData[$k]= $v['id'].'-goods-'.$v['number'];
                }
                $stringData = array_merge($projectPackData,$goodsStringData);
                $string = implode(',',$stringData);
                $getData['string'] = $string;
            }
            try{
                Db::name('qt_data_package')->where('id',$getData['id'])->update($getData);
                //删除原有套餐并新增
                Db::name('qt_data_package_item')->where('package_id',$getData['id'])->delete();
                $goods = [];
                $i = 0;
                foreach ($projectRes as $key=>$value){
                    $productIDs = explode(',',$value['id']);
                    foreach ($productIDs as $k=>$v){
                        $product = explode('-',$v);
                        $name = explode(',',$value['name']);
                        $goods[$i]['package_id'] = $getData['id'];
                        $goods[$i]['item_id'] = $product[1];
                        $goods[$i]['item_type'] = $product[0];
                        $goods[$i]['name'] = $name[$k];
                        $goods[$i]['number'] = $value['number'];
                        $goods[$i]['price'] = $value['price'];
                        $goods[$i]['creat_time'] = time();
                        $i ++;
                    }
                }
                Db::name('qt_data_package_item')->insertAll($goods);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('修改失败','',204);
            }
            $this->result('修改成功','',200);
        }
        $this->result('无效的请求','',204);
    }



    /**
     * 删除套餐
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数','',204);
            }
            try{
                Db::startTrans();
                //删除套餐
                Db::name('qt_data_package')->where('id',$getData['id'])->delete();
                //删除套餐商品
                Db::name('qt_data_package_item')->where('package_id',$getData['id'])->delete();
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('删除失败','',204);
            }
            $this->result('删除成功','',200);
        }
    }



    /**
     * 删除套餐商品
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete_project()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $getData = $this->request->post();
            if(empty($getData['package_item_id'])){
                $this->result('缺少参数','',204);
            }
            $del = Db::name('qt_data_package_item')->where('id',$getData['package_item_id'])->delete();
            if($del){
                $this->result('删除成功','',200);
            }
            $this->result('删除失败','',204);
        }
    }




}